package com.example.demo.listener;

import com.example.demo.globalvar.LocalCache;
import com.example.demo.model.dataobject.FileMetadataDO;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;

import java.io.File;

public class FileChangeListener extends FileAlterationListenerAdaptor {

    @Override
    public void onDirectoryCreate(File directory) {
        System.out.println("文件夹创建: " + directory.getAbsolutePath());
        saveCaffeine(directory);
    }

    @Override
    public void onDirectoryDelete(File directory) {
        System.out.println("文件夹删除: " + directory.getAbsolutePath());
        deleteCaffeine(directory);
    }

    @Override
    public void onFileCreate(File file) {
        System.out.println("文件创建: " + file.getAbsolutePath());
        saveCaffeine(file);
    }

    @Override
    public void onFileDelete(File file) {
        System.out.println("文件删除: " + file.getAbsolutePath());
        deleteCaffeine(file);
    }


    private void saveCaffeine(File file) {
        if (LocalCache.DELETE_LOCAL_CACHE.getIfPresent(file.getPath())!= null) {
            LocalCache.DELETE_LOCAL_CACHE.invalidate(file.getPath());
        } else {
            // 扩展名
            String extension = file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf(".") + 1);

            if (file.isDirectory()) {
                extension = "";
            }

            // 保存文件元数据本地缓存
            LocalCache.ADD_LOCAL_CACHE.put(file.getPath(),FileMetadataDO.builder()
                    .fileName(file.getName())
                    .filePath(file.getAbsolutePath())
                    .fileSize(file.length())
                    .modifiedTime(System.currentTimeMillis())
                    .isDirectory(file.isDirectory())
                    .extension(extension)
                    .build());
        }
    }

    private void deleteCaffeine(File file) {
        // 检查缓存中是否包含该文件的路径
        if (LocalCache.ADD_LOCAL_CACHE.getIfPresent(file.getPath()) != null) {
            LocalCache.ADD_LOCAL_CACHE.invalidate(file.getPath());
        }else {
            // 扩展名
            String extension = file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf(".") + 1);

            if (file.isDirectory()) {
                extension = "";
            }
            // 保存文件元数据本地缓存
            LocalCache.DELETE_LOCAL_CACHE.put(file.getPath(),FileMetadataDO.builder()
                    .fileName(file.getName())
                    .filePath(file.getAbsolutePath())
                    .fileSize(file.length())
                    .modifiedTime(System.currentTimeMillis())
                    .isDirectory(file.isDirectory())
                    .extension(extension)
                    .build());
        }
    }
}
